package org.seed.quantum.socket;

import java.nio.channels.CompletionHandler;

final class WriteCompletionHandler implements CompletionHandler<Integer, SocketSession> {

    @Override
    public void completed(final Integer result, final SocketSession session) {
        try {
            NetMonitor monitor = session.getServerConfig().getMonitor();
            if (monitor != null) {
                monitor.afterWrite(session, result);
            }
            session.writeCompleted();
        } catch (Exception e) {
            failed(e, session);
        }
    }


    @Override
    public void failed(Throwable exc, SocketSession session) {
        try {
            session.getServerConfig().getProcessor().stateEvent(session, SocketStateEnum.OUTPUT_EXCEPTION, exc);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            session.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
